<template>
  <a-modal
    :visible="visible"
    :title="title"
    :hide-cancel="true"
    :unmount-on-close="true"
    @cancel="handleCancel"
    @before-ok="handleBeforeOk"
  >
    <a-form ref="deptRef" :model="formData">
      <a-form-item
        field="name"
        label="部门名称"
        validate-trigger="input"
        :rules="[
          {
            required: true,
            message: '部门名称必填',
          },
        ]"
      >
        <a-input v-model="formData.name" />
      </a-form-item>
      <a-form-item
        field="entName"
        label="部门简称"
        validate-trigger="input"
        :rules="[
          {
            required: true,
            message: '部门简称必填',
          },
        ]"
      >
        <a-input v-model="formData.entName" />
      </a-form-item>
      <a-form-item
        field="parentId"
        label="上级部门"
        :rules="[
          {
            required: true,
            message: '上级部门必填',
          },
        ]"
      >
        <!-- 部门选择器 -->
        <OrgSelector
          v-model:deptId="formData.parentId"
          :disabled="disableOrg"
          @change="handleDeptChange"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
  import { computed, ref, watch } from 'vue';
  import OrgSelector from '@/components/org-selector/index.vue';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { Message } from '@arco-design/web-vue';
  import { SelectDept, addOrgs, OrgServiceRecord, modifyOrg } from '../api';
  // import { useI18n } from 'vue-i18n';
  // import useLoading from '@/hooks/loading';

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
    form: {
      type: Object,
      default() {
        return { name: '', entName: '', parentId: '' };
      },
    },
  });
  const emit = defineEmits(['update:visible', 'refresh']);

  const formData = ref<SelectDept>({ ...props.form } as SelectDept);
  watch(
    () => props.form,
    (n) => {
      formData.value = { ...n } as SelectDept;
    }
  );
  const deptRef = ref<FormInstance>();

  const disableOrg = computed(() => {
    return !!props.form.parentId;
  });

  const handleBeforeOk = async (done: any) => {
    const res = await deptRef.value?.validate();
    if (!res) {
      let flg = false;
      let msg = '添加成功';
      // 编辑组织机构
      if (formData.value.operator === 'edit') {
        flg = await editOrg();
        msg = '修改成功';
      } else if (formData.value.operator === 'add') {
        if (formData.value.pathNo) {
          // 新增子组织机构
          flg = await addSubOrg();
        } else {
          // 新增根组织机构
          flg = await addOrg();
        }
      } else if (formData.value.operator === 'addSub') {
        // 新增子组织机构
        flg = await addSubOrg();
      } else {
        // nothing to do here
      }
      if (flg) {
        Message.success(msg);
        emit('update:visible', false);
        emit('refresh');
      }
      done();
    }
  };
  const editOrg = async () => {
    const params = {
      ...formData.value.content,
      name: formData.value.name,
      entName: formData.value.entName,
    };
    const res = await modifyOrg(params);
    return !!res.status;
  };
  // 新增根节点下的组织机构，即最大的组织机构
  const addOrg = async () => {
    const params = {
      name: formData.value.name,
      entName: formData.value.entName,
      parentName: '根节点',
      pathName: `.根节点.${formData.value.name}.`,
    };
    const res = await addOrgs(params);
    return !!res.status;
  };
  const addSubOrg = async () => {
    const params = {
      name: formData.value.name,
      entName: formData.value.entName,
      parentName: formData.value.parentName,
      parentNo: formData.value.parentId,
      pathName: `${formData.value.pathName}${formData.value.name}.`,
      pathNo: `${formData.value.pathNo}`,
    };
    const res = await addOrgs(params);
    return !!res.status;
  };
  const handleCancel = () => {
    emit('update:visible', false);
  };

  const handleDeptChange = (val: OrgServiceRecord) => {
    if (val && val.content) {
      formData.value.parentName = val.content.parentName;
      formData.value.pathName = val.content.pathName;
      formData.value.pathNo = val.content.pathNo;
    }
  };
</script>

<script lang="ts">
  export default {
    name: 'OrgInfo',
  };
</script>
